<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col v-if="userInfo.userId === '1'" :span="4">
                <sys-org-tree
                    @treeClick="treeClick"
                />
            </el-col>
            <el-col :span="userInfo.userId === '1'? 20 : 24" :xs="24">
                <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" class="search-form"
                         label-width="68px"
                         size="small">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input
                            v-model="queryParams.roleName"
                            clearable
                            placeholder="请输入角色名称"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="权限字符" prop="roleKey">
                        <el-input
                            v-model="queryParams.roleKey"
                            clearable
                            placeholder="请输入权限字符"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="角色状态" prop="status">
                        <el-radio-group v-model="queryParams.status" @change="handleQuery">
                            <el-radio label="">全部</el-radio>
                            <el-radio
                                v-for="dict in dict.type.sys_normal_disable"
                                :key="dict.value"
                                :label="dict.value"
                            >{{ dict.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="创建时间">
                        <el-date-picker
                            v-model="dateRange"
                            end-placeholder="结束日期"
                            range-separator="-"
                            start-placeholder="开始日期"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:role:add']"
                            icon="el-icon-plus"
                            plain
                            size="mini"
                            type="primary"
                            @click="handleAdd"
                        >新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:role:remove']"
                            :disabled="multiple"
                            icon="el-icon-delete"
                            plain
                            size="mini"
                            type="danger"
                            @click="handleDelete"
                        >删除
                        </el-button>
                    </el-col>
                    <!--            <el-col :span="1.5">-->
                    <!--                <el-button-->
                    <!--                    type="warning"-->
                    <!--                    plain-->
                    <!--                    icon="el-icon-download"-->
                    <!--                    size="mini"-->
                    <!--                    @click="handleExport"-->
                    <!--                    v-hasPermi="['system:role:export']"-->
                    <!--                >导出-->
                    <!--                </el-button>-->
                    <!--            </el-col>-->
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-adaptive v-loading="loading" :data="roleList" :stripe='true' border height="200px"
                          @selection-change="handleSelectionChange">
                    <el-table-column align="center" type="selection" width="55"/>
                    <!--            <el-table-column label="角色编号" prop="roleId" header-align="center" width="120"/>-->
                    <el-table-column :show-overflow-tooltip="true" header-align="center" label="角色名称" prop="roleName"/>
                    <el-table-column :show-overflow-tooltip="true" header-align="center" label="权限字符" prop="roleKey"/>
                    <el-table-column align="center" label="显示顺序" prop="roleSort" width="100"/>
                    <el-table-column align="center" label="状态" width="100">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                active-value="0"
                                inactive-value="1"
                                @change="handleStatusChange(scope.row)"
                            ></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建时间" prop="createTime" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="280">
                        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
                            <el-button
                                v-hasPermi="['system:role:edit']"
                                icon="el-icon-edit"
                                size="mini"
                                type="text"
                                @click="handleUpdate(scope.row)"
                            >权限分配
                            </el-button>
                            <el-button
                                v-hasPermi="['system:role:edit']"
                                icon="el-icon-user"
                                size="mini"
                                type="text"
                                @click="handleAuthUser(scope.row)"
                            >分配人员
                            </el-button>
                            <el-button
                                v-hasPermi="['system:role:remove']"
                                icon="el-icon-delete"
                                size="mini"
                                type="text"
                                @click="handleDelete(scope.row)"
                            >删除
                            </el-button>
                            <!--                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"-->
                            <!--                                 v-hasPermi="['system:role:edit']">-->
                            <!--                        <span class="el-dropdown-link">-->
                            <!--                          <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多-->
                            <!--                        </span>-->
                            <!--                        <el-dropdown-menu slot="dropdown">-->
                            <!--                            <el-dropdown-item command="handleAuthUser" icon="el-icon-user"-->
                            <!--                                              v-hasPermi="['system:role:edit']">分配用户-->
                            <!--                            </el-dropdown-item>-->
                            <!--                        </el-dropdown-menu>-->
                            <!--                    </el-dropdown>-->
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total>0"
                    :limit.sync="queryParams.pageSize"
                    :page.sync="queryParams.pageNum"
                    :total="total"
                    @pagination="getList"
                />
            </el-col>
        </el-row>
        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="1200px"
                   @close="chooseClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="roleKey">
                      <span slot="label">
                        <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                          <i class="el-icon-question"></i>
                        </el-tooltip>
                        权限字符
                      </span>
                            <el-input v-model="form.roleKey" placeholder="请输入权限字符"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="角色顺序" prop="roleSort">
                            <el-input-number v-model="form.roleSort" :min="0" controls-position="right"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio
                            v-for="dict in dict.type.sys_normal_disable"
                            :key="dict.value"
                            :label="dict.value"
                        >{{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择服务">
                    <div style="height: 440px;overflow: auto">
                        <el-row>
                            <el-col :span="16">
                                <div class="el-transfer-panel">
                                    <p class="el-transfer-panel__header">
                                        <label class="el-checkbox">
                                            <span class="el-checkbox__input">
                                                <input aria-hidden="false"
                                                       class="el-checkbox__original"
                                                       type="checkbox"
                                                       value="">
                                            </span>
                                            <span class="el-checkbox__label">
                                                待选服务
                                                <span>{{ leftChoose.length }}/{{ chooseService.length }}</span>
                                            </span>
                                        </label>
                                    </p>
                                    <div class="el-transfer-panel__body">
                                        <el-empty v-if="chooseService.length === 0" description="无数据"
                                                  style="margin-bottom: -310px;"/>
                                        <el-checkbox-group v-model="leftChoose" @change="leftChooseChange">
                                            <div v-for="(item, index) in chooseService">
                                                <el-checkbox :key="item.roleGroupId" :label="item"
                                                             class="check-service">{{ item.roleGroupName }}
                                                </el-checkbox>
                                            </div>
                                        </el-checkbox-group>
                                    </div>
                                </div>
                                <el-button :disabled="leftChoose.length === 0" size="mini" type="primary"
                                           @click="theSelected">选中
                                </el-button>
                                <el-button :disabled="rightChoose.length === 0" size="mini" type="danger"
                                           @click="theCancel">删除
                                </el-button>
                                <div class="el-transfer-panel">
                                    <p class="el-transfer-panel__header">
                                        <label class="el-checkbox">
                                            <span class="el-checkbox__input">
                                                <input aria-hidden="false"
                                                       class="el-checkbox__original"
                                                       type="checkbox"
                                                       value="">
                                            </span>
                                            <span class="el-checkbox__label">
                                                已服务
                                                <span>{{ rightChoose.length }}/{{ haveChooseService.length }}</span>
                                            </span>
                                        </label>
                                    </p>
                                    <div class="el-transfer-panel__body">
                                        <el-empty v-if="haveChooseService.length === 0" description="无数据"
                                                  style="margin-bottom: -310px;"/>
                                        <el-checkbox-group v-model="rightChoose" @change="rightChooseChange">
                                            <div v-for="(item, index) in haveChooseService">
                                                <el-checkbox :key="item.roleGroupId" :label="item"
                                                             class="check-service">{{ item.roleGroupName }}
                                                </el-checkbox>
                                            </div>
                                        </el-checkbox-group>
                                    </div>
                                </div>
                            </el-col>
                            <el-col v-if="!isAdd" :span="8">
                                <div class="tree-div">
                                    <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">
                                        展开/折叠
                                    </el-checkbox>
                                    <el-checkbox v-model="menuNodeAll"
                                                 @change="handleCheckedTreeNodeAll($event, 'menu')">
                                        全选/全不选
                                    </el-checkbox>
                                    <el-checkbox v-model="menuCheckStrictly"
                                                 @change="handleCheckedTreeConnect($event, 'menu')">
                                        父子联动
                                    </el-checkbox>
                                </div>
                                <div class="group-menu-tree">
                                    <el-empty v-if="menuOptions.length === 0" description="无数据"
                                              style="margin-bottom: -310px;"/>
                                    <div v-else>
                                        <el-tree
                                            ref="menu"
                                            :check-strictly="!form.menuCheckStrictly"
                                            :data="menuOptions"
                                            :props="defaultProps"
                                            class="tree-border"
                                            default-expand-all
                                            empty-text="加载中，请稍候"
                                            node-key="id"
                                            show-checkbox
                                        ></el-tree>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>


                    </div>

                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">保 存</el-button>
                <el-button size="small" @click="chooseClose">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listRole,
    getRole,
    delRole,
    addRole,
    updateRole,
    dataScope,
    changeRoleStatus,
    deptTreeSelect
} from "@/api/system/role";
import {selectChooseRoleGroupMenu} from "@/api/system/menu";
import {selectList, getNotExistsRoleGroup} from "@/api/system/group";
import {roleGroupMenuTree} from '@/api/system/roleGroupMenu'
import {delChooseRoleGroup} from '@/api/system/chooseRoleGroup'

export default {
    name: "Role",
    dicts: ['sys_normal_disable'],
    data () {
        return {
            // 登录用户信息
            userInfo: this.$store.state.user.userInfo,
            // 权限菜单数量
            menuCount: 0,
            // 是否点击新增按钮
            isAdd: false,
            // 已选择服务id
            roleGroupId: '',
            // 菜单树选择项是否关联显示
            menuCheckStrictly: true,
            // 待选择服务列表
            chooseService: [],
            // 已选择服务列表
            haveChooseService: [],
            // 左侧选中
            leftChoose: [],
            // 右侧选中
            rightChoose: [],
            // 页面临时删除的服务列表
            deleteList: [],
            value: [],
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 角色表格数据
            roleList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否显示弹出层（数据权限）
            openDataScope: false,
            menuExpand: true,
            menuNodeAll: false,
            // 日期范围
            dateRange: [],
            // 菜单列表
            menuOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                roleName: undefined,
                roleKey: undefined,
                status: ''
            },
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 表单校验
            rules: {
                roleName: [
                    {required: true, message: "角色名称不能为空", trigger: "blur"}
                ],
                roleKey: [
                    {required: true, message: "权限字符不能为空", trigger: "blur"}
                ],
                roleSort: [
                    {required: true, message: "角色顺序不能为空", trigger: "blur"}
                ]
            }
        };
    },
    created () {
        if (this.userInfo.orgId) {
            this.queryParams.orgId = this.userInfo.orgId
            this.getList()
        }
    },
    methods: {
        /** 左侧科室树节点点击事件 */
        treeClick (obj) {
            this.queryParams.orgId = obj.id
            this.getList()
        },
        /** 获取自定义服务列表 */
        getRoleGroup () {
            let param = {'orgId': this.queryParams.orgId}
            selectList(param).then(res => {
                this.chooseService = res.data
            })
        },
        /** 获取已选择的自定义服务列表 */
        getNotExistsRoleGroup () {
            let param = {'roleId': this.form.roleId, 'orgId': this.queryParams.orgId}
            getNotExistsRoleGroup(param).then(res => {
                let data = res.data
                this.chooseService = data.list
                this.haveChooseService = data.haveChooseService
            })
        },
        // 角色状态修改
        handleStatusChange (row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(function () {
                return changeRoleStatus(row.roleId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        // 表单重置
        reset () {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([]);
            }
            this.menuExpand = true
            this.menuNodeAll = false
            this.form = {
                roleId: undefined,
                roleName: undefined,
                roleKey: undefined,
                roleSort: 0,
                status: "0",
                menuIds: [],
                deptIds: [],
                menuCheckStrictly: true,
                remark: undefined,
                orgId: this.queryParams.orgId
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.roleId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        // 更多操作触发
        handleCommand (command, row) {
            switch (command) {
                case "handleAuthUser":
                    this.handleAuthUser(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            if (!this.userInfo.orgId && !this.form.orgId) {
                return this.$modal.msgError("请先选择所属机构后再新增")
            }
            this.getRoleGroup()
            this.open = true;
            this.isAdd = true
            this.title = "添加角色";
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            this.form = row
            this.isAdd = false
            this.form.roleId = row.roleId
            this.title = "修改角色";
            this.getNotExistsRoleGroup()
            this.open = true;
        },
        /** 点击修改组织权限菜单选中树 */
        setPermissionsTree (roleId) {
            const roleMenu = this.getSelectChooseRoleGroupMenu(roleId);
            this.open = true;
            this.$nextTick(() => {
                console.log('this.menuOptions', this.menuOptions)
                roleMenu.then(res => {
                    let checkedKeys = res.data
                    if (checkedKeys.length === this.menuCount) {
                        this.menuNodeAll = true
                    } else {
                        this.menuNodeAll = false
                    }
                    checkedKeys.forEach((v) => {
                        this.$nextTick(() => {
                            this.$refs.menu.setChecked(v, true, false);
                        })
                    })
                });
            });
        },
        /** 根据角色ID查询菜单树结构 */
        getSelectChooseRoleGroupMenu (roleId) {
            let param = {"roleId": roleId, "roleGroupId": this.roleGroupId}
            return selectChooseRoleGroupMenu(param).then(response => {
                return response;
            });
        },
        // 树权限（展开/折叠）
        handleCheckedTreeExpand (value, type) {
            if (type == 'menu') {
                let treeList = this.menuOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
                }
            } else if (type == 'dept') {
                let treeList = this.deptOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll (value, type) {
            if (type == 'menu') {
                this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
            } else if (type == 'dept') {
                this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
            }
        },
        // 树权限（父子联动）
        handleCheckedTreeConnect (value, type) {
            if (type == 'menu') {
                this.form.menuCheckStrictly = value ? true : false;
            } else if (type == 'dept') {
                this.form.deptCheckStrictly = value ? true : false;
            }
        },
        /** 分配用户操作 */
        handleAuthUser: function (row) {
            const roleId = row.roleId;
            const businessType = '1';
            this.$router.push("/system/role-auth/user/" + this.queryParams.orgId + "/" + roleId + "/" + businessType);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.roleGroupId = this.roleGroupId
                    if (this.form.roleId !== undefined) {
                        if (this.rightChoose.length <= 0) {
                            return this.$modal.msgError("请勾选需要添加的权限数据后保存")
                        }
                        this.form.menuIds = this.getMenuAllCheckedKeys();
                        if (this.form.menuIds.length <= 0) {
                            return this.$modal.msgError("请勾选需要添加的权限数据后保存")
                        }
                        updateRole(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            // this.open = false;
                            this.getList();
                        });
                    } else {
                        if (this.haveChooseService.length <= 0) {
                            return this.$modal.msgError("请添加服务数据后保存")
                        }
                        let roleGroupIdArray = []
                        this.haveChooseService.forEach(item => {
                            let roleGroupId = item.roleGroupId
                            roleGroupIdArray.push(roleGroupId)
                        })
                        if (roleGroupIdArray.length > 0) {
                            this.form.roleGroupIdArray = roleGroupIdArray
                        }
                        console.log('this.form', this.form)
                        addRole(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.handleQuery();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const roleIds = row.roleId || this.ids;
            this.$modal.confirm('是否删除选中的数据项？').then(function () {
                return delRole(roleIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 左侧点击事件 */
        leftChooseChange (val) {
            console.log('leftChoose', this.leftChoose)
        },
        /** 右侧点击事件 */
        rightChooseChange (val) {
            if (this.rightChoose.length > 1) {
                this.rightChoose.splice(0, 1)
            }
            if (this.rightChoose.length === 1) {
                this.menuOptions = []
                let roleGroupId = this.rightChoose[0].roleGroupId
                this.roleGroupId = roleGroupId
                // 新增
                roleGroupMenuTree(roleGroupId).then(res => {
                    let data = res.data
                    this.menuCheckStrictly = data.menuCheckStrictly
                    this.menuOptions = data.treeList
                    this.menuCount = data.menuCount
                    if (this.form.roleId) {
                        // 修改
                        this.setPermissionsTree(this.form.roleId)
                    }
                })
            }
        },
        /** 选中事件 */
        theSelected () {
            if (this.leftChoose.length > 0) {
                this.leftChoose.forEach(item => {
                    this.haveChooseService.push(item)
                    this.$delete(this.chooseService, this.chooseService.indexOf(item))
                })
                this.leftChoose = []
            }
        },
        /** 删除已选择服务事件 */
        theCancel () {
            if (this.rightChoose.length > 0) {
                let param = {"roleId": this.form.roleId, "roleGroupId": this.rightChoose[0].roleGroupId}
                this.$modal.confirm("确定要删除名称为(" + this.rightChoose[0].roleGroupName + ")的服务吗？删除后所选权限不可恢复。").then(function () {
                    return delChooseRoleGroup(param);
                }).then(() => {
                    this.getList()
                    this.menuOptions = []
                    this.rightChoose.forEach(item => {
                        this.chooseService.push(item)
                        this.$delete(this.haveChooseService, this.haveChooseService.indexOf(item))
                    })
                    this.rightChoose = []
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {
                });
            }
        },
        /** 关闭自定义服务dialog */
        chooseClose () {
            this.open = false
            this.chooseService = []
            this.haveChooseService = []
            this.leftChoose = []
            this.rightChoose = []
            this.menuOptions = []
            this.reset();
        },
        /** 查询角色列表 */
        getList () {
            if (!this.queryParams.orgId) {
                return this.$modal.msgError("请先选择左侧所属机构后查询")
            }
            this.loading = true;
            listRole(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.roleList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                }
            );
        },
        // 所有菜单节点数据
        getMenuAllCheckedKeys () {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },

    }
}
;
</script>

<style scoped>
::v-deep .el-transfer-panel {
    width: 260px;
}

::v-deep .el-transfer-panel__body {
    height: 380px !important;
    overflow-y: auto;
}

::v-deep .el-transfer__buttons {
    padding: 0px;
}

::v-deep .el-checkbox-group {
    height: 100% !important;
}




.check-service {
    margin-left: 10px
}

</style>

